package com.atguigu.daijia.rules.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atguigu.daijia.model.form.rules.FeeRuleRequest;
import com.atguigu.daijia.model.form.rules.FeeRuleRequestForm;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponse;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponseVo;
import com.atguigu.daijia.rules.mapper.FeeRuleMapper;
import com.atguigu.daijia.rules.service.FeeRuleService;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FeeRuleServiceImpl implements FeeRuleService {


    //规则引擎对象
    @Autowired
    private KieContainer kieContainer;

    //计算订单金额
    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm calculateOrderFeeForm) {
        //封装输入对象
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        feeRuleRequest.setDistance(calculateOrderFeeForm.getDistance());
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        feeRuleRequest.setStartTime(sdf.format(calculateOrderFeeForm.getStartTime()));
        feeRuleRequest.setWaitMinute(calculateOrderFeeForm.getWaitMinute());
        //使用Drools规则引擎
        KieSession kieSession = kieContainer.newKieSession();
        //封装返回对象，设置为全局变量，在规则中发生改变在java代码中也会起作用
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        kieSession.setGlobal("feeRuleResponse",feeRuleResponse);
        //将对象插入到工作内存中
        kieSession.insert(feeRuleRequest);
        //触发规则
        kieSession.fireAllRules();
        //终止会话
        kieSession.dispose();
        //封装数据到FeeRuleResponseVo中
        FeeRuleResponseVo feeRuleResponseVo = BeanUtil.copyProperties(feeRuleResponse, FeeRuleResponseVo.class);
        return feeRuleResponseVo;
    }
}
